package com.ssy.lingxi.after.sale.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.ssy.lingxi.after.sale.entity.ReturnGoodsDO;
import com.ssy.lingxi.after.sale.entity.ReturnGoodsDetailAssociatedDO;
import com.ssy.lingxi.after.sale.entity.ReturnGoodsDetailDO;
import com.ssy.lingxi.after.sale.entity.ReturnGoodsRefundDetailDO;
import com.ssy.lingxi.after.sale.model.constant.*;
import com.ssy.lingxi.after.sale.model.vo.request.ReturnGoodsDetailPageVO;
import com.ssy.lingxi.after.sale.model.vo.request.ReturnGoodsDetailSetStatusVO;
import com.ssy.lingxi.after.sale.model.vo.response.*;
import com.ssy.lingxi.after.sale.repository.ReturnGoodsDetailMaterielRepository;
import com.ssy.lingxi.after.sale.repository.ReturnGoodsDetailRepository;
import com.ssy.lingxi.after.sale.repository.ReturnGoodsRepository;
import com.ssy.lingxi.after.sale.service.IReturnGoodsDetailService;
import com.ssy.lingxi.after.sale.utils.ParamVerifyUtils;
import com.ssy.lingxi.common.constant.basic.UserLoginSourceEnum;
import com.ssy.lingxi.common.constant.order.OrderPayChannelEnum;
import com.ssy.lingxi.common.constant.order.OrderPayTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 售后退货接口服务实现
 * @author 伍将
 * @date 2020/9/10
 * @version 2.0.0
 */
@Service
public class ReturnGoodsDetailServiceImpl implements IReturnGoodsDetailService {

    @Resource
    private ReturnGoodsDetailRepository repository;
    @Resource
    private ReturnGoodsDetailMaterielRepository returnGoodsDetailMaterielRepository;

    @Resource
    private ReturnGoodsRepository returnGoodsRepository;

    /**
     * 分页查询退货商品
     * @author 伍将
     * @date 2020/9/10
     * @param pageVO:
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnedGoodsQueryVO>>
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsDetailQueryVO>> pageList(UserLoginCacheDTO loginUser,ReturnGoodsDetailPageVO pageVO) {
        ReturnGoodsDO repairGoodsDO = returnGoodsRepository.findById(pageVO.getReturnId()).orElse(null);
        if(repairGoodsDO==null){
            return Wrapper.success(new PageData<>(0L, null));
        }
        // step 1: 组装查询条件
        Specification<ReturnGoodsDetailDO> spec =  (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("returnId").as(Long.class), pageVO.getReturnId()));
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // step 2: 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        // step 3: 分页查询数据
        Page<ReturnGoodsDetailDO> result = repository.findAll(spec, page);

        // step 4: 组装返回数据
        List<ReturnGoodsDetailQueryVO> resultList = result.getContent().stream().map(r -> {
            ReturnGoodsDetailQueryVO queryVO = new ReturnGoodsDetailQueryVO();
            queryVO.setReturnGoodsId(r.getId());
            queryVO.setOrderNo(r.getOrderNo());
            queryVO.setOrderId(r.getOrderId());
            queryVO.setOrderRecordId(r.getOrderRecordId());
            queryVO.setProductId(r.getProductId());
            queryVO.setProductName(r.getProductName());
            queryVO.setCategory(r.getCategory());
            queryVO.setBrand(r.getBrand());
            queryVO.setUnit(r.getUnit());
            queryVO.setPurchaseCount(r.getPurchaseCount());
            queryVO.setPurchasePrice(r.getPurchasePrice());
            queryVO.setPurchaseAmount(NumberUtil.mul(r.getPurchaseCount(),r.getPurchasePrice()));
            queryVO.setPayAmount(r.getPayAmount());
            queryVO.setReturnCount(r.getReturnCount());
            queryVO.setRefundAmount(r.getRefundList().stream().mapToDouble(ReturnGoodsRefundDetailDO::getRefundAmount).reduce(0D, NumberUtil::add));
            queryVO.setIsNeedReturn(r.getIsNeedReturn());
            queryVO.setReturnReason(r.getReturnReason());
            queryVO.setNeedReturnName(CommonBooleanEnum.getMessage(r.getIsNeedReturn()));
            queryVO.setIsHasTax(r.getIsHasTax());
            queryVO.setTaxRate(r.getTaxRate());
            queryVO.setType(r.getType());
            queryVO.setDeliveryCount(r.getDeliveryCount());
            queryVO.setNoDeliveryCount(NumberUtil.sub(r.getReturnCount(),r.getDeliveryCount()));
            queryVO.setReceiveCount(r.getReceiveCount());
            queryVO.setSubCount(NumberUtil.sub(r.getDeliveryCount(),r.getReceiveCount()));
            if (r.getRefundList() != null) {
                List<ReturnGoodsPayVO> payVOList = r.getRefundList().stream().map(o -> {
                    ReturnGoodsPayVO entity = new ReturnGoodsPayVO();
                    entity.setPayCount(o.getPayCount());
                    entity.setPayNode(o.getPayNode());
                    entity.setPayRatio(o.getPayRatio());
                    entity.setPayAmount(o.getPayAmount());
                    entity.setPayWay(o.getPayWay());
                    entity.setPayWayName(OrderPayTypeEnum.getNameByCode(o.getPayWay()));
                    entity.setChannel(o.getChannel());
                    entity.setChannelName(OrderPayChannelEnum.getNameByCode(o.getChannel()));
                    entity.setRefundAmount(o.getRefundAmount());
                    entity.setPayTime((o.getPayTime() != null && o.getPayTime() > 0) ? DateUtil.format(DateUtil.date(o.getPayTime()), "yyyy-MM-dd HH:mm") : "");
                    return entity;
                }).collect(Collectors.toList());
                queryVO.setPayList(payVOList);
            }
            return queryVO;
        }).collect(Collectors.toList());
        //合同类型订单（询价、竞价、招标合同）填充关联商品信息
        if(ParamVerifyUtils.isContractOrderType(repairGoodsDO.getOrderType())){
            List<ReturnGoodsDetailAssociatedDO> materielDOS = returnGoodsDetailMaterielRepository.findByReturnId(pageVO.getReturnId());
            if(CollectionUtil.isNotEmpty(materielDOS)){
                resultList.forEach(o -> materielDOS.forEach(m ->{
                    if(o.getReturnGoodsId().equals(m.getReturnDetailId())){
                        o.setAssociatedProductId(m.getProductId());
                        o.setAssociatedProductName(m.getProductName());
                        o.setAssociatedBrand(m.getBrand());
                        o.setAssociatedCategory(m.getCategory());
                        o.setAssociatedUnit(m.getUnit());
                        o.setAssociatedType(m.getType());
                    }
                }));
            }
        }
        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * App端分页查询退货商品
     * @author 伍将
     * @date 2021/3/18
     * @param pageVO: 分页请求参数
     * @return 操作结果
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsDetailAppQueryVO>> pageListByApp(ReturnGoodsDetailPageVO pageVO) {
// step 1: 组装查询条件
        Specification<ReturnGoodsDetailDO> spec =  (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("returnId").as(Long.class), pageVO.getReturnId()));
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // step 2: 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        // step 3: 分页查询数据
        Page<ReturnGoodsDetailDO> result = repository.findAll(spec, page);

        // step 4: 组装返回数据
        List<ReturnGoodsDetailAppQueryVO> resultList = result.getContent().stream().map(r -> {
            ReturnGoodsDetailAppQueryVO queryVO = new ReturnGoodsDetailAppQueryVO();
            queryVO.setReturnGoodsId(r.getId());
            queryVO.setOrderNo(r.getOrderNo());
            queryVO.setOrderRecordId(r.getOrderRecordId());
            queryVO.setProductId(r.getProductId());
            queryVO.setProductName(r.getProductName());
            queryVO.setCategory(r.getCategory());
            queryVO.setBrand(r.getBrand());
            queryVO.setUnit(r.getUnit());
            queryVO.setPurchaseCount(r.getPurchaseCount());
            queryVO.setPurchasePrice(r.getPurchasePrice());
            queryVO.setPurchaseAmount(NumberUtil.mul(r.getPurchaseCount() , r.getPurchasePrice()));
            queryVO.setPayAmount(r.getPayAmount());
            queryVO.setReturnCount(r.getReturnCount());
            queryVO.setRefundAmount(r.getRefundList().stream().mapToDouble(ReturnGoodsRefundDetailDO::getRefundAmount).sum());
            queryVO.setIsNeedReturn(r.getIsNeedReturn());
            queryVO.setReturnReason(r.getReturnReason());
            queryVO.setNeedReturnName(CommonBooleanEnum.getMessage(r.getIsNeedReturn()));
            if (r.getRefundList() != null) {
                List<ReturnGoodsAppPayVO> payVOList = r.getRefundList().stream().map(o -> {
                    ReturnGoodsAppPayVO entity = new ReturnGoodsAppPayVO();
                    entity.setPayCount(o.getPayCount());
                    entity.setPayNode(o.getPayNode());
                    entity.setPayRatio(o.getPayRatio());
                    entity.setPayAmount(o.getPayAmount());
                    entity.setPayWay(o.getPayWay());
                    entity.setPayWayName(OrderPayTypeEnum.getNameByCode(o.getPayWay()));
                    entity.setChannel(o.getChannel());
                    entity.setChannelName(OrderPayChannelEnum.getNameByCode(o.getChannel()));
                    entity.setRefundAmount(o.getRefundAmount());
                    entity.setPayTime(o.getPayTime());
                    return entity;
                }).collect(Collectors.toList());
                queryVO.setPayList(payVOList);
            }
            return queryVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * 设置需要退货
     * @author 伍将
     * @date 2020/9/25
     * @param user:
     * @param setStatusVO:
     * @return com.ssy.lingxi.common.response.Wrapper
     **/
    @Override
    public Wrapper<Void> setNeedReturnGoods(UserLoginCacheDTO user, ReturnGoodsDetailSetStatusVO setStatusVO) {
        if (setStatusVO == null) {
            throw new BusinessException(ResponseCode.AS_RETURN_GOODS_DETAIL_SET_RETURN_PARAM_EMPTY);
        }
        if (!setStatusVO.getIsNeed().equals(CommonBooleanEnum.NO.getCode())
                && !setStatusVO.getIsNeed().equals(CommonBooleanEnum.YES.getCode())) {
            throw new BusinessException(ResponseCode.AS_RETURN_GOODS_DETAIL_SET_RETURN_PARAM_ERROR);
        }
        ReturnGoodsDO returnDO = returnGoodsRepository.findById(setStatusVO.getReturnId()).orElse(null);
        if (returnDO == null) {
            throw new BusinessException(ResponseCode.AS_RETURN_GOODS_NOT_EXIST);
        }
        if (!returnDO.getOuterStatus().equals(ReturnGoodsOuterStatusEnum.TO_BE_CONFIRM.getCode())
                || !returnDO.getInnerStatus().equals(ReturnGoodsInnerStatusEnum.TO_BE_SUBMIT.getCode())) {
            throw new BusinessException(ResponseCode.AS_RETURN_UN_ALLOW_SET_RETURN_GOODS);
        }
        ReturnGoodsDetailDO detailDO = repository.findById(setStatusVO.getReturnGoodsId()).orElse(null);
        if (detailDO == null) {
            throw new BusinessException(ResponseCode.AS_RETURN_GOODS_NOT_EXIST);
        }
        // 如果换货id与换货商品所属换货id不匹配，则说明参数错误
        if (!returnDO.getId().equals(detailDO.getReturnId())) {
            throw new BusinessException(ResponseCode.AS_RETURN_GOODS_DETAIL_SET_RETURN_PARAM_ERROR);
        }
        detailDO.setIsNeedReturn(setStatusVO.getIsNeed());
        repository.saveAndFlush(detailDO);

        return Wrapper.success();
    }

    /**
     * 采购商获取退货统计
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO:
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsStatisticsVO>>
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsStatisticsVO>> pageStatisticsByConsumer(ReturnGoodsDetailPageVO pageVO) {
        return pageStatistics(pageVO);
    }

    /**
     * 供应商获取退货统计
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO:
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsStatisticsVO>>
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsStatisticsVO>> pageStatisticsBySupplier(ReturnGoodsDetailPageVO pageVO) {
        return pageStatistics(pageVO);
    }

    /**
     * 获取退货统计
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO:
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsStatisticsVO>>
     **/
    private Wrapper<PageData<ReturnGoodsStatisticsVO>> pageStatistics(ReturnGoodsDetailPageVO pageVO) {
        // step 1: 组装查询条件
        Specification<ReturnGoodsDetailDO> spec =  (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("returnId").as(Long.class), pageVO.getReturnId()));
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // step 2: 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        // step 3: 分页查询数据
        Page<ReturnGoodsDetailDO> result = repository.findAll(spec, page);

        // step 4: 组装返回数据
        List<ReturnGoodsStatisticsVO> resultList = result.getContent().stream().map(r -> {
            ReturnGoodsStatisticsVO queryVO = new ReturnGoodsStatisticsVO();
            queryVO.setOrderNo(r.getOrderNo());
            queryVO.setProductId(r.getProductId());
            queryVO.setProductName(r.getProductName());
            queryVO.setCategory(r.getCategory());
            queryVO.setBrand(r.getBrand());
            queryVO.setUnit(r.getUnit());
            queryVO.setReturnCount(r.getReturnCount());
            queryVO.setDeliveryCount(r.getDeliveryCount());
            queryVO.setUnDeliveryCount(r.getReturnCount() - r.getDeliveryCount());
            queryVO.setReceiveCount(r.getReceiveCount());
            queryVO.setDifferenceCount(r.getDeliveryCount() - r.getReceiveCount());

            return queryVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * 采购商分页查询退款
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO: 
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsRefundVO>>
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsRefundVO>> pageRefundByConsumer(ReturnGoodsDetailPageVO pageVO) {
        return pageRefund(pageVO);
    }

    /**
     * 供应商分页查询退款
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO: 
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsRefundVO>>
     **/
    @Override
    public Wrapper<PageData<ReturnGoodsRefundVO>> pageRefundBySupplier(ReturnGoodsDetailPageVO pageVO) {
        return pageRefund(pageVO);
    }

    /**
     * 分页查询退款
     * @author 伍将
     * @date 2020/10/19
     * @param pageVO:
     * @return com.ssy.lingxi.common.response.Wrapper<com.ssy.lingxi.common.response.PageData < com.ssy.lingxi.after.sale.model.vo.response.ReturnGoodsRefundVO>>
     **/
    private Wrapper<PageData<ReturnGoodsRefundVO>> pageRefund(ReturnGoodsDetailPageVO pageVO) {
        // step 1: 组装查询条件
        Specification<ReturnGoodsDetailDO> spec =  (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("returnId").as(Long.class), pageVO.getReturnId()));
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // step 2: 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        // step 3: 分页查询数据
        Page<ReturnGoodsDetailDO> result = repository.findAll(spec, page);

        // step 4: 组装返回数据
        List<ReturnGoodsRefundVO> resultList = result.getContent().stream().map(r -> {
            ReturnGoodsRefundVO queryVO = new ReturnGoodsRefundVO();
            queryVO.setOrderNo(r.getOrderNo());
            queryVO.setProductId(r.getProductId());
            queryVO.setProductName(r.getProductName());
            queryVO.setCategory(r.getCategory());
            queryVO.setBrand(r.getBrand());
            queryVO.setUnit(r.getUnit());
            queryVO.setPurchasePrice(r.getPurchasePrice());
            queryVO.setPurchaseCount(r.getPurchaseCount());
            queryVO.setPurchaseAmount(NumberUtil.mul(r.getPurchaseCount() , r.getPurchasePrice()));
            queryVO.setPayAmount(r.getPayAmount());
            queryVO.setReturnCount(r.getReturnCount());
            //支付明细
            List<ReturnGoodsRefundDetailVO> detailList = r.getRefundList().stream().map(o -> {
                ReturnGoodsRefundDetailVO detail = new ReturnGoodsRefundDetailVO();
                detail.setRefundId(o.getId());
                detail.setPayCount(o.getPayCount());
                detail.setPayNode(o.getPayNode());
                detail.setPayRatio(o.getPayRatio());
                detail.setPayAmount(o.getPayAmount());
                detail.setPayWay(o.getPayWay());
                detail.setPayWayName(OrderPayTypeEnum.getNameByCode(o.getPayWay()));
                detail.setChannel(o.getChannel());
                detail.setChannelName(OrderPayChannelEnum.getNameByCode(o.getChannel()));
                detail.setRefundAmount(o.getRefundAmount());
                detail.setInnerStatus(o.getInnerStatus());
                detail.setInnerStatusName(ReturnGoodsRefundInnerStatusEnum.getMessage(o.getInnerStatus()));
                detail.setOuterStatus(o.getOuterStatus());
                detail.setOuterStatusName(ReturnGoodsRefundOuterStatusEnum.getMessage(o.getOuterStatus()));
                detail.setRefundTime((o.getRefundTime() != null && o.getRefundTime() > 0) ? DateUtil.format(DateUtil.date(o.getRefundTime()), "yyyy-MM-dd HH:mm") : "");
                return detail;
            }).collect(Collectors.toList());
            queryVO.setDetailList(detailList);
            queryVO.setRefundAmount(detailList.stream().mapToDouble(ReturnGoodsRefundDetailVO::getRefundAmount).sum());

            return queryVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * 获取退款列表
     * @author 伍将
     * @date 2020/12/5
     * @param returnId:
     * @return 退款列表
     **/
    @Override
    public List<ReturnGoodsRefundVO> getDetailList(UserLoginCacheDTO user, ReturnGoodsDO returnDO, Long returnId) {

        List<ReturnGoodsDetailDO> returnGoodsDetailDOList = repository.findByReturnId(returnId);

        return returnGoodsDetailDOList.stream().map(r -> {
            ReturnGoodsRefundVO queryVO = new ReturnGoodsRefundVO();
            queryVO.setOrderNo(r.getOrderNo());
            queryVO.setProductId(r.getProductId());
            queryVO.setProductName(r.getProductName());
            queryVO.setCategory(r.getCategory());
            queryVO.setBrand(r.getBrand());
            queryVO.setUnit(r.getUnit());
            queryVO.setPurchasePrice(r.getPurchasePrice());
            queryVO.setPurchaseCount(r.getPurchaseCount());
            queryVO.setPurchaseAmount(NumberUtil.mul(r.getPurchaseCount() , r.getPurchasePrice()));
            queryVO.setPayAmount(r.getPayAmount());
            queryVO.setReturnCount(r.getReturnCount());
            queryVO.setSkuPic(r.getSkuPic());
            //支付明细，支付记录按照支付次数顺序排序
            List<ReturnGoodsRefundDetailVO> detailList;
            detailList = r.getRefundList().stream()
                    .sorted(Comparator.comparing(ReturnGoodsRefundDetailDO::getPayCount))
                    .map(o -> {
                        ReturnGoodsRefundDetailVO detail = new ReturnGoodsRefundDetailVO();
                        detail.setPayId(o.getPayId());
                        detail.setExternalState(o.getExternalState());
                        detail.setRefundId(o.getId());
                        detail.setPayCount(o.getPayCount());
                        detail.setPayNode(o.getPayNode());
                        detail.setPayRatio(o.getPayRatio());
                        detail.setPayAmount(o.getPayAmount());
                        detail.setPayWay(o.getPayWay());
                        detail.setPayWayName(OrderPayTypeEnum.getNameByCode(o.getPayWay()));
                        detail.setChannel(o.getChannel());
                        detail.setChannelName(OrderPayChannelEnum.getNameByCode(o.getChannel()));
                        detail.setRefundAmount(o.getRefundAmount());
                        detail.setInnerStatus(o.getInnerStatus());
                        detail.setInnerStatusName(ReturnGoodsRefundInnerStatusEnum.getMessage(o.getInnerStatus()));
                        detail.setOuterStatus(o.getOuterStatus());
                        detail.setOuterStatusName(ReturnGoodsRefundOuterStatusEnum.getMessage(o.getOuterStatus()));
                        detail.setRefundTime((o.getRefundTime() != null && o.getRefundTime() > 0) ? DateUtil.format(DateUtil.date(o.getRefundTime()), "yyyy-MM-dd HH:mm") : "");
                        detail.setPayProve(o.getPayProve());
                        Integer canRefund = CommonBooleanEnum.NO.getCode();
                        // 已支付的数据进行验证是否允许退款
                        if (PayExternalStateEnum.CONFIRM_RECEIPT.getCode().equals(o.getExternalState())) {
                            // 如果当前登录账户为平台账号,支付方式为平台代收，则当前数据允许退款
                            if (UserLoginSourceEnum.BUSINESS_MANAGEMENT_PLATFORM.getCode().equals(user.getLoginSource()) && PayRuleConfigurationEnum.PLATFORM.getCode().equals(o.getPayRuleId())) {
                                canRefund = CommonBooleanEnum.YES.getCode();
                            }
                            // 如果当前登录账户为web端登录账号,支付方式为会员直接到账代收,且收款方为同一个会员,则当前数据允许退款
                            else if (UserLoginSourceEnum.BUSINESS_WEB.getCode().equals(user.getLoginSource()) && PayRuleConfigurationEnum.MEMBER.getCode().equals(o.getPayRuleId())
                                    && user.getMemberId().equals(returnDO.getParentMemberId()) && user.getMemberRoleId().equals(returnDO.getParentMemberRoleId())) {
                                canRefund = CommonBooleanEnum.YES.getCode();
                            }
                        }
                        detail.setCanRefund(canRefund);
                        return detail;
                    }).collect(Collectors.toList());
            queryVO.setDetailList(detailList);
            Double refundAmount = detailList.stream().map(ReturnGoodsRefundDetailVO::getRefundAmount).reduce(0d, NumberUtil::add);
            queryVO.setRefundAmount(refundAmount);
            return queryVO;
        }).collect(Collectors.toList());
    }
}
